<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>周一数据报告</title>
    <script type="text/javascript" src="../js/jquery.js"></script>
    <script type="text/javascript" src="../js/echarts.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <link rel="stylesheet" href="../css/style.css">

    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f8f9fa;
            margin: 0;
            padding: 0;
        }

        .report-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .report-header {
            background: #2c3e50;
            color: white;
            padding: 15px 20px;
            border-radius: 5px 5px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .report-title {
            margin: 0;
            font-size: 22px;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .report-time {
            font-size: 14px;
        }

        .download-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .download-btn:hover {
            background-color: #2980b9;
        }

        .download-btn:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }

        .report-nav {
            background: #34495e;
            padding: 10px 20px;
        }

        .report-nav ul {
            list-style: none;
            margin: 0;
            padding: 0;
            display: flex;
            flex-wrap: wrap;
        }

        .report-nav li {
            margin-right: 15px;
            margin-bottom: 5px;
        }

        .report-nav a {
            color: #ecf0f1;
            text-decoration: none;
            font-size: 14px;
        }

        .report-nav a:hover {
            color: #3498db;
        }

        .report-section {
            background: white;
            border-radius: 0 0 5px 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            margin-bottom: 25px;
            padding: 20px;
        }

        .section-title {
            color: #2c3e50;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-top: 0;
            margin-bottom: 20px;
            font-size: 18px;
        }

        .analysis-text {
            line-height: 1.6;
            color: #555;
            margin-bottom: 15px;
        }

        .chart-container {
            height: 400px;
            margin-top: 20px;
            position: relative;
        }

        .chart-loading {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10;
        }

        .data-highlight {
            color: #e74c3c;
            font-weight: bold;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            font-size: 14px;
        }

        .data-table th,
        .data-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }

        .data-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }

        .data-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .warning-note {
            background-color: #fff3e0;
            padding: 12px 15px;
            border-left: 4px solid #ff4d00;
            margin: 15px 0;
            border-radius: 3px;
            font-size: 14px;
            color: red;
        }

        .grid-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        @media (max-width: 768px) {
            .grid-container {
                grid-template-columns: 1fr;
            }

            .header-right {
                flex-direction: column;
                gap: 10px;
                align-items: flex-end;
            }
            
            .chart-container {
                height: 300px;
            }
        }

        /* 打印优化样式 */
        @media print {
            body {
                background-color: white;
                padding: 0;
                margin: 0;
            }

            .report-container {
                max-width: 100%;
                padding: 10px;
                box-shadow: none;
            }

            .report-header,
            .report-nav {
                display: none;
            }

            .report-section {
                page-break-inside: avoid;
                margin-bottom: 15px;
                box-shadow: none;
                border: 1px solid #eee;
            }

            .chart-container {
                height: 300px;
            }
            
            .no-print {
                display: none !important;
            }
        }

        /* PDF生成临时元素样式 */
        .temp-pdf-container {
            position: absolute;
            left: -9999px;
            width: 210mm;
            padding: 20px;
            background-color: white;
        }

        .pdf-title {
            text-align: center;
            margin-bottom: 20px;
            color: #2c3e50;
            font-size: 24px;
        }

        .pdf-date {
            text-align: right;
            margin-bottom: 15px;
            font-size: 14px;
        }

        .home-btn {
            color: white;
            text-decoration: none;
            font-size: 16px;
            opacity: 0.7;
            transition: opacity 0.3s;
            padding: 5px;
        }

        .home-btn:hover {
            opacity: 1;
        }
        
        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border-left-color: #3498db;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>

<body>
    <div class="report-container">
        <div class="report-header">
            <h1 class="report-title">智微生物后台 - 周一检测报告</h1>
            <div class="header-right">
                <a href="../index.html" class="logo-btn" title="返回主页">
                    <img src="../img/home.png" alt="主页" width="20">
                </a>
                <div class="report-time" id="showTime"></div>
                <button class="download-btn" id="downloadReport">报告下载</button>
            </div>
        </div>

        <div class="report-nav">
            <ul>
                <li><a href="../templates/Monday.html">周一</a></li>
                <li><a href="../templates/Tuesday.html">周二</a></li>
                <li><a href="../templates/Wedesday.html">周三</a></li>
                <li><a href="../templates/Thursday.html">周四</a></li>
                <li><a href="../templates/Friday.html">周五</a></li>
                <li><a href="../templates/Saturday.html">周六</a></li>
                <li><a href="../templates/Sunday.html">周日</a></li>
                <li><a href="../templates/total.html">汇总</a></li>
            </ul>
        </div>

        <!-- 数据概览 -->
        <div class="report-section" id="reportContent">
            <h2 class="section-title">今日检测概览</h2>
            <div class="grid-container">
                <div>
                    <div class="analysis-text">
                        <p>今日共检测 <span class="data-highlight">152</span> 个样品，其中 <span class="data-highlight">34</span>
                            个(22.4%)超出国家标准。</p>
                        <p>主要超标菌种：</p>
                        <ul>
                            <li>金黄色葡萄球菌：16例(47.1%)</li>
                            <li>大肠杆菌：8例(23.5%)</li>
                            <li>沙门氏菌：4例(11.8%)</li>
                            <li>李斯特菌：3例(8.8%)</li>
                            <li>志贺氏菌：2例(5.9%)</li>
                            <li>表皮芽杆菌：1例(2.9%)</li>
                        </ul>
                    </div>
                </div>
                <div>
                    <div class="analysis-text">
                        <p>当日重点关注：</p>
                        <ul>
                            <li>生产线B超标率高达38%</li>
                            <li>下午2-4点检测的超标样品占全天的52%</li>
                            <li>批次PRD-2023-06-19有9例超标</li>
                            <li>李斯特菌超标率较上周上升15%</li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="chart-container" id="overviewChart">
                <div class="chart-loading no-print">
                    <div class="spinner"></div>
                </div>
            </div>
        </div>

        <!-- 菌落分布 -->
        <div class="report-section">
            <h2 class="section-title">菌落含量分析</h2>
            <div class="analysis-text">
                <p>当日检测中，7种菌落含量分布如下：</p>
                <table class="data-table">
                    <tr>
                        <th>菌种名称</th>
                        <th>平均含量(cfu/g)</th>
                        <th>最高含量(cfu/g)</th>
                        <th>国家标准(cfu/g)</th>
                        <th>超标样品数</th>
                    </tr>
                    <tr>
                        <td>大肠杆菌</td>
                        <td>23.5</td>
                        <td>45</td>
                        <td>30</td>
                        <td>8</td>
                    </tr>
                    <tr>
                        <td>金黄色葡萄球菌</td>
                        <td>88.2</td>
                        <td>118</td>
                        <td>50</td>
                        <td>16</td>
                    </tr>
                    <tr>
                        <td>表皮芽杆菌</td>
                        <td>42.3</td>
                        <td>68</td>
                        <td>60</td>
                        <td>1</td>
                    </tr>
                    <tr>
                        <td>沙门氏菌</td>
                        <td>28.7</td>
                        <td>47</td>
                        <td>40</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>克罗诺干菌</td>
                        <td>31.2</td>
                        <td>42</td>
                        <td>35</td>
                        <td>0</td>
                    </tr>
                    <tr>
                        <td>李斯特菌</td>
                        <td>25.8</td>
                        <td>38</td>
                        <td>30</td>
                        <td>3</td>
                    </tr>
                    <tr>
                        <td>志贺氏菌</td>
                        <td>18.6</td>
                        <td>32</td>
                        <td>25</td>
                        <td>2</td>
                    </tr>
                </table>
            </div>
            <div class="chart-container" id="distributionChart">
                <div class="chart-loading no-print">
                    <div class="spinner"></div>
                </div>
            </div>
        </div>

        <!-- 超标分析 -->
        <div class="report-section">
            <h2 class="section-title">超标样品分析</h2>
            <div class="analysis-text">
                <p>当日超标样品呈现以下特征：</p>
                <ul>
                    <li>76%来自生产线B(下午班次)</li>
                    <li>62%集中在4个生产批次</li>
                    <li>超标样品中82%检出金黄色葡萄球菌或大肠杆菌</li>
                    <li>李斯特菌超标率较上周显著上升</li>
                </ul>
            </div>
            <div class="warning-note">
                <strong>紧急通知：</strong>生产线B下午班次的消毒设备疑似故障，且李斯特菌含量异常升高，建议立即停机检查并加强环境消毒。
            </div>
            <div class="chart-container" id="exceedChart">
                <div class="chart-loading no-print">
                    <div class="spinner"></div>
                </div>
            </div>
        </div>

        <!-- 预测分析 -->
        <div class="report-section">
            <h2 class="section-title">菌落数量预测分析</h2>
            <div class="analysis-text">
                <p>基于历史数据和机器学习模型，我们对未来3天的菌落数量进行了预测：</p>
                <div class="warning-note">
                    <strong>预测重点：</strong> 预计金黄色葡萄球菌和沙门氏菌在未来48小时内可能继续超标，建议提前加强消毒措施。
                </div>
            </div>
            <div class="chart-container" id="predictionChart">
                <div class="chart-loading no-print">
                    <div class="spinner"></div>
                </div>
            </div>

            <div class="grid-container" style="color: #e74c3c;">
                <div>
                    <h3 class="section-title" style="font-size:16px; margin-top:0;">预测准确性指标</h3>
                    <table class="data-table">
                        <tr>
                            <th>评估指标</th>
                            <th>值</th>
                            <th>说明</th>
                        </tr>
                        <tr>
                            <td>MAE (平均绝对误差)</td>
                            <td>4.2 cfu/g</td>
                            <td>预测值与实际值的平均差异</td>
                        </tr>
                        <tr>
                            <td>RMSE (均方根误差)</td>
                            <td>5.8 cfu/g</td>
                            <td>对较大误差更敏感的指标</td>
                        </tr>
                        <tr>
                            <td>R² (决定系数)</td>
                            <td>0.92</td>
                            <td>1表示完美预测，>0.8为优秀</td>
                        </tr>
                        <tr>
                            <td>预测准确率</td>
                            <td>88.5%</td>
                            <td>超标/不超标判断正确率</td>
                        </tr>
                    </table>
                </div>
                <div>
                    <h3 class="section-title" style="font-size:16px; margin-top:0;">关键预测结果</h3>
                    <ul class="analysis-text">
                        <li>预计明日金黄色葡萄球菌平均含量：<span class="data-highlight">96.4±5.2 cfu/g</span> (超标概率92%)</li>
                        <li>预计沙门氏菌峰值可能达到：<span class="data-highlight">51.3±3.8 cfu/g</span></li>
                        <li>生产线B的超标风险最高：<span class="data-highlight">风险指数87/100</span></li>
                        <li>下午班次(14:00-18:00)是风险最高时段</li>
                    </ul>
                    <div class="warning-note" style="margin-top:15px;">
                        <strong>行动建议：</strong> 提前增加生产线B下午班次的消毒频次，准备备用消毒设备。
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 时间显示
        function updateTime() {
            const dt = new Date();
            const y = dt.getFullYear();
            const mt = String(dt.getMonth() + 1).padStart(2, '0');
            const day = String(dt.getDate()).padStart(2, '0');
            const h = String(dt.getHours()).padStart(2, '0');
            const m = String(dt.getMinutes()).padStart(2, '0');
            const s = String(dt.getSeconds()).padStart(2, '0');
            document.getElementById("showTime").innerHTML = `${y}/${mt}/${day} ${h}:${m}:${s}`;
        }
        updateTime();
        setInterval(updateTime, 1000);

        // 隐藏加载动画
        function hideLoading(chartId) {
            const container = document.getElementById(chartId);
            if (container) {
                const loading = container.querySelector('.chart-loading');
                if (loading) loading.style.display = 'none';
            }
        }

        // 数据概览图表
        var overviewChart = echarts.init(document.getElementById('overviewChart'));
        overviewChart.setOption({
            title: {
                text: '当日检测结果分布',
                left: 'center',
                textStyle: {
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 0,
                data: ['合格样品', '金黄色葡萄球菌超标', '大肠杆菌超标', '沙门氏菌超标', '李斯特菌超标', '志贺氏菌超标', '其他菌种超标']
            },
            series: [
                {
                    name: '检测结果',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 5,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '16',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        { value: 118, name: '合格样品', itemStyle: { color: '#27ae60' } },
                        { value: 16, name: '金黄色葡萄球菌超标', itemStyle: { color: '#e74c3c' } },
                        { value: 8, name: '大肠杆菌超标', itemStyle: { color: '#f39c12' } },
                        { value: 4, name: '沙门氏菌超标', itemStyle: { color: '#9b59b6' } },
                        { value: 3, name: '李斯特菌超标', itemStyle: { color: '#3498db' } },
                        { value: 2, name: '志贺氏菌超标', itemStyle: { color: '#1abc9c' } },
                        { value: 1, name: '其他菌种超标', itemStyle: { color: '#e67e22' } }
                    ]
                }
            ]
        });
        overviewChart.on('finished', function() {
            hideLoading('overviewChart');
        });

        // 菌落分布图表
        var distributionChart = echarts.init(document.getElementById('distributionChart'));
        distributionChart.setOption({
            title: {
                text: '7种菌落含量分布(当日)',
                left: 'center',
                textStyle: {
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function (params) {
                    let result = params[0].name + '<br/>';
                    params.forEach(param => {
                        result += `${param.seriesName}: ${param.value} cfu/g<br/>`;
                    });
                    return result;
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['大肠杆菌', '金黄色葡萄球菌', '表皮芽杆菌', '沙门氏菌', '克罗诺干菌', '李斯特菌', '志贺氏菌'],
                axisLabel: {
                    interval: 0,
                    rotate: 30
                }
            },
            yAxis: {
                type: 'value',
                name: '含量(cfu/g)'
            },
            series: [
                {
                    name: '平均含量',
                    type: 'bar',
                    data: [23.5, 88.2, 42.3, 28.7, 31.2, 25.8, 18.6],
                    itemStyle: {
                        color: '#3498db'
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}'
                    }
                },
                {
                    name: '最高含量',
                    type: 'bar',
                    data: [45, 118, 68, 47, 42, 38, 32],
                    itemStyle: {
                        color: '#e74c3c'
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}'
                    }
                },
                {
                    name: '国家标准',
                    type: 'line',
                    data: [30, 50, 60, 40, 35, 30, 25],
                    symbol: 'none',
                    lineStyle: {
                        color: '#2ecc71',
                        width: 2,
                        type: 'dashed'
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: function (params) {
                            return '标准:' + params.value;
                        }
                    }
                }
            ]
        });
        distributionChart.on('finished', function() {
            hideLoading('distributionChart');
        });

        // 超标分析图表
        var exceedChart = echarts.init(document.getElementById('exceedChart'));
        exceedChart.setOption({
            title: {
                text: '超标菌种来源分析',
                left: 'center',
                textStyle: {
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['金黄色葡萄球菌', '大肠杆菌', '沙门氏菌', '李斯特菌', '志贺氏菌'],
                bottom: 0
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['生产线A', '生产线B', '生产线C', '生产线D']
            },
            yAxis: {
                type: 'value',
                name: '超标样品数'
            },
            series: [
                {
                    name: '金黄色葡萄球菌',
                    type: 'bar',
                    stack: 'total',
                    data: [2, 11, 2, 1],
                    itemStyle: {
                        color: '#e74c3c'
                    }
                },
                {
                    name: '大肠杆菌',
                    type: 'bar',
                    stack: 'total',
                    data: [1, 5, 1, 1],
                    itemStyle: {
                        color: '#f39c12'
                    }
                },
                {
                    name: '沙门氏菌',
                    type: 'bar',
                    stack: 'total',
                    data: [0, 3, 1, 0],
                    itemStyle: {
                        color: '#9b59b6'
                    }
                },
                {
                    name: '李斯特菌',
                    type: 'bar',
                    stack: 'total',
                    data: [0, 2, 1, 0],
                    itemStyle: {
                        color: '#3498db'
                    }
                },
                {
                    name: '志贺氏菌',
                    type: 'bar',
                    stack: 'total',
                    data: [0, 1, 1, 0],
                    itemStyle: {
                        color: '#1abc9c'
                    }
                }
            ]
        });
        exceedChart.on('finished', function() {
            hideLoading('exceedChart');
        });

        // 响应式调整
        function resizeCharts() {
            overviewChart.resize();
            distributionChart.resize();
            exceedChart.resize();
            predictionChart.resize();
        }
        
        window.addEventListener('resize', function () {
            setTimeout(resizeCharts, 200);
        });

        // 改进的PDF生成函数
        async function generatePDF() {
            const btn = document.getElementById('downloadReport');
            btn.disabled = true;
            btn.textContent = '生成中...';
            
            // 显示所有图表加载状态
            document.querySelectorAll('.chart-loading').forEach(el => {
                el.style.display = 'flex';
            });

            try {
                const dt = new Date();
                const fileName = `智微生物检测报告_${dt.getFullYear()}${(dt.getMonth() + 1).toString().padStart(2, '0')}${dt.getDate().toString().padStart(2, '0')}.pdf`;

                const { jsPDF } = window.jspdf;
                const pdf = new jsPDF('p', 'mm', 'a4');

                // 1. 添加封面页
                pdf.setFillColor(44, 62, 80);
                pdf.rect(0, 0, pdf.internal.pageSize.getWidth(), pdf.internal.pageSize.getHeight(), 'F');
                pdf.setTextColor(255, 255, 255);
                pdf.setFontSize(28);
                pdf.text('智微生物检测报告', 105, 100, { align: 'center' });
                pdf.setFontSize(18);
                pdf.text('周一数据报告', 105, 120, { align: 'center' });
                pdf.setFontSize(14);
                pdf.text(`生成日期: ${dt.getFullYear()}年${dt.getMonth() + 1}月${dt.getDate()}日`, 105, 140, { align: 'center' });

                // 2. 添加内容页
                pdf.addPage();

                // 创建临时打印优化版HTML
                const printContainer = document.createElement('div');
                printContainer.className = 'temp-pdf-container';

                // 克隆报告内容并优化打印样式
                const contentClone = document.getElementById('reportContent').cloneNode(true);
                
                // 移除所有加载动画
                contentClone.querySelectorAll('.chart-loading').forEach(el => el.remove());

                // 添加打印专用标题
                const printHeader = document.createElement('h1');
                printHeader.className = 'pdf-title';
                printHeader.textContent = '智微生物 - 周一检测报告';
                contentClone.insertBefore(printHeader, contentClone.firstChild);

                // 添加打印日期
                const printDate = document.createElement('div');
                printDate.className = 'pdf-date';
                printDate.textContent = `报告日期: ${dt.getFullYear()}年${dt.getMonth() + 1}月${dt.getDate()}日`;
                contentClone.insertBefore(printDate, contentClone.children[1]);

                // 处理图表 - 先获取图表图片数据
                const charts = ['overviewChart', 'distributionChart', 'exceedChart'];
                const chartImages = {};

                // 等待所有图表准备好
                await Promise.all(charts.map(chartId => {
                    const chart = echarts.getInstanceByDom(document.getElementById(chartId));
                    return new Promise(resolve => {
                        chart.on('finished', () => {
                            chartImages[chartId] = chart.getDataURL({
                                type: 'png',
                                pixelRatio: 2,
                                backgroundColor: '#fff'
                            });
                            resolve();
                        });
                        chart.resize(); // 触发重绘确保图表是最新状态
                    });
                }));

                // 替换图表为图片
                const chartContainers = contentClone.querySelectorAll('.chart-container');
                for (let i = 0; i < chartContainers.length; i++) {
                    const img = document.createElement('img');
                    img.src = chartImages[charts[i]];
                    img.style.width = '100%';
                    img.style.height = 'auto';
                    chartContainers[i].innerHTML = '';
                    chartContainers[i].appendChild(img);
                }

                // 添加到打印容器
                printContainer.appendChild(contentClone);
                document.body.appendChild(printContainer);

                // 使用html2canvas生成高质量图片
                const canvas = await html2canvas(printContainer, {
                    scale: 2,
                    logging: false,
                    useCORS: true,
                    allowTaint: true,
                    scrollX: 0,
                    scrollY: 0,
                    onclone: (clonedDoc) => {
                        // 确保克隆的文档中图表容器有正确的高度
                        clonedDoc.querySelectorAll('.chart-container').forEach(el => {
                            el.style.height = '300px';
                        });
                    }
                });

                // 添加到PDF
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = pdf.internal.pageSize.getWidth() - 20;
                const imgHeight = (canvas.height * imgWidth) / canvas.width;

                pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);

                // 3. 添加总结页
                pdf.addPage();
                pdf.setFontSize(16);
                pdf.setTextColor(0, 0, 0);
                pdf.text('检测结果总结', 20, 20);

                pdf.setFontSize(12);
                const summaryText = [
                    '1. 今日共检测152个样品，其中34个(22.4%)超出国家标准',
                    '2. 主要超标菌种为金黄色葡萄球菌(16例)和大肠杆菌(8例)',
                    '3. 生产线B超标率高达38%，建议立即检查消毒设备',
                    '4. 李斯特菌含量较上周上升15%，需关注潜在污染源',
                    '5. 下午2-4点检测的超标样品占全天的52%',
                    '',
                    '建议措施:',
                    '- 立即停机检查生产线B的消毒设备',
                    '- 对超标批次产品进行复检',
                    '- 加强生产环境的微生物监测',
                    '- 召开质量分析会议'
                ];

                let yPos = 40;
                summaryText.forEach(text => {
                    pdf.text(text, 20, yPos);
                    yPos += 7;
                });

                // 添加页脚
                pdf.setFontSize(10);
                pdf.setTextColor(100, 100, 100);
                pdf.text('智微生物科技有限公司 - 内部保密文件', 105, 287, { align: 'center' });

                // 保存PDF
                pdf.save(fileName);

            } catch (err) {
                console.error('生成报告失败:', err);
                alert('报告生成失败: ' + err.message);
            } finally {
                // 清理临时元素
                const tempContainer = document.querySelector('.temp-pdf-container');
                if (tempContainer) {
                    document.body.removeChild(tempContainer);
                }
                
                btn.disabled = false;
                btn.textContent = '报告下载';
                
                // 隐藏加载状态
                document.querySelectorAll('.chart-loading').forEach(el => {
                    el.style.display = 'none';
                });
            }
        }

        // 预测分析图表
        var predictionChart = echarts.init(document.getElementById('predictionChart'));
        predictionChart.setOption({
            title: {
                text: '菌落数量预测与实际对比',
                left: 'center',
                textStyle: {
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    let result = params[0].axisValue + '<br/>';
                    params.forEach(param => {
                        const seriesName = param.seriesName;
                        let value = param.value;
                        let marker = param.marker;

                        if (seriesName.includes('预测')) {
                            // 显示预测区间
                            if (param.dataIndex >= 7) { // 预测数据点
                                const range = seriesName === '金黄色葡萄球菌预测' ? '±5.2' :
                                    seriesName === '沙门氏菌预测' ? '±3.8' : '±4.5';
                                value = `${value} ${range}`;
                            }
                        }

                        result += `${marker} ${seriesName}: ${value} cfu/g<br/>`;

                        // 添加超标警告
                        if (seriesName.includes('实际') && param.dataIndex < 7) {
                            const standard = seriesName.includes('金黄色葡萄球菌') ? 50 :
                                seriesName.includes('沙门氏菌') ? 40 : 30;
                            if (param.value > standard) {
                                result += `<span style="color:#e74c3c;margin-left:20px;">↑ 超标 ${(param.value - standard).toFixed(1)} cfu/g</span><br/>`;
                            }
                        }
                    });
                    return result;
                }
            },
            legend: {
                data: ['金黄色葡萄球菌实际', '金黄色葡萄球菌预测', '沙门氏菌实际', '沙门氏菌预测', '警戒线'],
                bottom: 0
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['D-6', 'D-5', 'D-4', 'D-3', 'D-2', 'D-1', '今日', 'D+1', 'D+2', 'D+3'],
                axisLabel: {
                    formatter: function (value, index) {
                        if (index >= 7) { // 预测日期加粗显示
                            return `{bold|${value}}`;
                        }
                        return value;
                    },
                    rich: {
                        bold: {
                            fontWeight: 'bold',
                            color: '#e74c3c'
                        }
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: '菌落含量(cfu/g)'
            },
            series: [
                {
                    name: '金黄色葡萄球菌实际',
                    type: 'line',
                    data: [45, 52, 48, 68, 72, 65, 88, null, null, null],
                    symbol: 'circle',
                    symbolSize: 6,
                    itemStyle: {
                        color: '#e74c3c'
                    },
                    lineStyle: {
                        width: 2
                    },
                    markLine: {
                        silent: true,
                        data: [{
                            yAxis: 50,
                            name: '金黄色葡萄球菌标准',
                            lineStyle: {
                                color: '#e74c3c',
                                type: 'dashed'
                            },
                            label: {
                                position: 'end',
                                formatter: '标准: 50 cfu/g'
                            }
                        }]
                    }
                },
                {
                    name: '金黄色葡萄球菌预测',
                    type: 'line',
                    data: [null, null, null, null, null, null, 88, 96, 102, 94],
                    symbol: 'none',
                    lineStyle: {
                        color: '#e74c3c',
                        type: 'dashed',
                        width: 2
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(231, 76, 60, 0.3)' },
                            { offset: 1, color: 'rgba(231, 76, 60, 0.1)' }
                        ])
                    },
                    markPoint: {
                        data: [
                            {
                                coord: ['D+1', 96],
                                symbol: 'triangle',
                                symbolSize: 10,
                                itemStyle: { color: '#e74c3c' },
                                label: {
                                    formatter: '预测峰值',
                                    position: 'top'
                                }
                            }
                        ]
                    }
                },
                {
                    name: '沙门氏菌实际',
                    type: 'line',
                    data: [28, 31, 25, 32, 29, 35, 42, null, null, null],
                    symbol: 'circle',
                    symbolSize: 6,
                    itemStyle: {
                        color: '#3498db'
                    },
                    lineStyle: {
                        width: 2
                    },
                    markLine: {
                        silent: true,
                        data: [{
                            yAxis: 40,
                            name: '沙门氏菌标准',
                            lineStyle: {
                                color: '#3498db',
                                type: 'dashed'
                            },
                            label: {
                                position: 'end',
                                formatter: '标准: 40 cfu/g'
                            }
                        }]
                    }
                },
                {
                    name: '沙门氏菌预测',
                    type: 'line',
                    data: [null, null, null, null, null, null, 42, 47, 51, 45],
                    symbol: 'none',
                    lineStyle: {
                        color: '#3498db',
                        type: 'dashed',
                        width: 2
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(52, 152, 219, 0.3)' },
                            { offset: 1, color: 'rgba(52, 152, 219, 0.1)' }
                        ])
                    }
                }
            ]
        });
        predictionChart.on('finished', function() {
            hideLoading('predictionChart');
        });

        // 绑定下载按钮
        document.getElementById('downloadReport').addEventListener('click', generatePDF);
    </script>
</body>

</html>